package com.gitee.mars.marsquickframe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.mars.marsquickframe.entity.SysUser;
import com.gitee.mars.marsquickframe.exception.WorkException;
import com.gitee.mars.marsquickframe.mapper.SysUserMapper;
import com.gitee.mars.marsquickframe.request.SysUserLoginRequest;
import com.gitee.mars.marsquickframe.request.SysUserRequest;
import com.gitee.mars.marsquickframe.response.SysUserResponse;
import com.gitee.mars.marsquickframe.response.base.PageInfo;
import com.gitee.mars.marsquickframe.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Objects;


/**
 * SysUser 实现层
 *
 * @Author wq
 * @Date 2021-03-15
 **/
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    @Override
    public SysUserResponse login(SysUserLoginRequest request) {
        //查询该用户
        SysUser sysUser = baseMapper.selectNickname(request.getNickname());
        if (Objects.isNull(sysUser)) {
            throw new WorkException("该用户还未注册,请注册");
        }
        if (!sysUser.getPassword().equals(request.getPassword())) {
            throw new WorkException("请输入正确的密码");
        }
        SysUserResponse sysUserResponse = new SysUserResponse();
        sysUserResponse.setAvatar(sysUser.getAvatar());
        sysUserResponse.setUserId(sysUser.getId());
        sysUserResponse.setNickname(sysUser.getNickname());
        return sysUserResponse;
    }

    @Override
    public PageInfo<SysUser> listUser(SysUserRequest request) {
        IPage<SysUser> page = new Page<>(request.getPageNumber(), request.getPageSize());
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(request.getUserId())) {
            wrapper.eq(SysUser::getId, request.getUserId());
        }
        if (StringUtils.isNotEmpty(request.getNickname())) {
            wrapper.like(SysUser::getNickname, request.getNickname());
        }
        IPage<SysUser> sysUserIPage = baseMapper.selectPage(page, wrapper);
        if (!CollectionUtils.isEmpty(sysUserIPage.getRecords())) {
            return new PageInfo<>(page.getTotal(), sysUserIPage.getRecords());
        }
        return null;
    }
}